package ru.maksb.exchange.service;

import java.net.Authenticator.RequestorType;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ru.maksb.exchange.domain.ClientInfo;
import ru.maksb.exchange.domain.request.NewOrderRequest;
import ru.maksb.exchange.domain.request.Request;
import ru.maksb.exchange.exceptions.MessageParseException;

public class MessageHandler {
    private final static Logger logger = LoggerFactory.getLogger(MessageHandler.class);
    private BlockingQueue<String> messagesToSend;
    private BlockingQueue<Request> requests;
    private ClientInfo clientInfo;

    public MessageHandler(BlockingQueue<String> messagesToSend, 
                          BlockingQueue<Request> requests,
                          ClientInfo clientInfo) {
        this.messagesToSend = messagesToSend;
        this.requests = requests;
        this.clientInfo = clientInfo;
    }

    public void handle(BlockingQueue<Request> requests, String message,
            AtomicBoolean serverWorkerRunning) {
        logger.debug("Client> {}", message);
        Request request = null;
        try {
            request = MessageParser.parseRequest(message);
            request.setClientId(clientInfo.getName());
            switch (request.getRequestType()) {
            case HEARTBEAT:
                //TODO: heartbeat handling;
                break;
            case ORDER_NEW:
                try {
                    messagesToSend.put(ResponseFactory.newOrderResultOk((NewOrderRequest) request));
                } catch (InterruptedException e1) {}
            default:
                try {
                    requests.put(request);
                } catch (InterruptedException e) {}
                break;
            }
        } catch (MessageParseException e) {
            logger.error("cannot parse message", e);
            try {
                messagesToSend.put(ResponseFactory.invalidMessage("-1"));
            } catch (InterruptedException e1) {}
            return;
        }
    }

}
